package com.can.utils;

import com.baomidou.mybatisplus.annotations.TableField;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Desription Map工具类
 * @Author can
 * @Date 2018/10/19
 * @Version 1.0
 */
public class CustomerBeanUtils {

    /**
     * 实体类转成map，null字段不处理
     * @param entity
     * @return
     */
    public static Map<String, Object> beanConvertMap(Object entity){
        Map<String, Object> result = new LinkedHashMap<String,Object>();
        if (null == entity) {
            return result;
        }
        // 获取所有字段
        Field[] fields = entity.getClass().getDeclaredFields();
        try{
            for(int i = 0; ArrayUtils.isNotEmpty(fields) && i < fields.length; i++) {
                fields[i].setAccessible(true);
                Object value = fields[i].get(entity);
                if(null == value){
                    continue;
                }
                // 判断字段上面是否有需要的注解
                boolean fieldHasAnno = fields[i].isAnnotationPresent(TableField.class);
                if(!fieldHasAnno){
                    result.put(fields[i].getName(), value);
                    continue;
                }
                // 获取字段上面的注解值
                TableField fieldAnno = fields[i].getAnnotation(TableField.class);
                result.put(fieldAnno.value(), value);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return result;
    }
}
